<template>
  <div class="home-page">
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-expand navbar-dark w-100">
      <div class="container">
        <a class="navbar-brand" href="#">
          家谱管理系统
        </a>
        <div class="navbar-nav ms-auto">
          <div class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
              <i class="fas fa-user me-2"></i>{{ userId }}
            </a>
            <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
              <li>
                <a class="dropdown-item" @click.prevent="editProfile" href="#">
                  <i class="fas fa-user-edit me-2"></i>编辑个人信息
                </a>
              </li>
              <li>
                <a class="dropdown-item" @click.prevent="handleLogout" href="#">
                  <i class="fas fa-sign-out-alt me-2"></i>退出登录
                </a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </nav>

    <!-- 主要内容区域 -->
    <div class="main-content container">
      <h1 class="text-center text-white">请选择要进行的操作</h1>
      <div class="operation-cards">
        <div class="operation-card" @click="createGenealogy">
          <div class="icon-wrapper">
            <i class="fas fa-plus"></i>
          </div>
          <h2>创建家谱</h2>
          <p>创建一个新的家谱记录</p>
        </div>
        <div class="operation-card" @click="viewGenealogy">
          <div class="icon-wrapper">
            <i class="fas fa-book"></i>
          </div>
          <h2>查看家谱</h2>
          <p>浏览已有的家谱记录</p>
        </div>
      </div>
      <div v-if="activeFunction === 'familySelect'" class="family-select">
        <h3>家族选择</h3>
        
        <!-- 加载中提示 -->
        <div v-if="loading" class="text-center py-5">
          <div class="spinner-border text-white" role="status">
            <span class="visually-hidden">加载中...</span>
          </div>
          <p class="mt-3 text-white">正在加载家族数据...</p>
        </div>
        
        <!-- 错误提示 -->
        <div v-else-if="error" class="alert alert-danger" role="alert">
          <i class="fas fa-exclamation-triangle me-2"></i>
          {{ error }}
          <button class="btn btn-sm btn-outline-danger ms-3" @click="loadGenealogyData">
            <i class="fas fa-sync-alt me-1"></i>重试
          </button>
        </div>
        
        <!-- 无数据提示 -->
        <div v-else-if="genealogyList.length === 0" class="family-placeholder text-center text-white">
          <i class="fas fa-home fa-3x mb-3"></i>
          <p>您还没有创建任何家族</p>
          <p class="text-muted small">当前用户ID: {{ userId || '未登录' }}</p>
          <button class="btn btn-primary mt-3" @click="showCreateGenealogyForm">
            <i class="fas fa-plus me-2"></i>创建新家谱
          </button>
        </div>
        
        <!-- 家族列表 -->
        <div v-else class="family-list">
          <div v-for="genealogy in genealogyList" :key="genealogy.genealogyId" 
               class="family-item" @click="selectGenealogy(genealogy)">
            <div class="family-icon">
              <i class="fas fa-home"></i>
            </div>
            <div class="family-info">
              <h4>{{ genealogy.genealogyName }}</h4>
              <p>创建时间: {{ formatDate(genealogy.createTime) }}</p>
              <p v-if="genealogy.description" class="description">{{ genealogy.description }}</p>
            </div>
          </div>
          
          <!-- 创建新家族按钮 -->
          <div class="family-item add-family" @click="showCreateGenealogyForm">
            <div class="family-icon add-icon">
              <i class="fas fa-plus"></i>
            </div>
            <div class="family-info">
              <h4>创建新家谱</h4>
              <p>添加一个新的家谱记录</p>
            </div>
          </div>
        </div>
        
        <!-- 创建家谱表单模态框 -->
        <div class="modal fade show" v-if="showGenealogyForm" style="display: block;">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title">创建新家谱</h5>
                <button type="button" class="btn-close" @click="closeGenealogyForm"></button>
              </div>
              <div class="modal-body">
                <form @submit.prevent="createGenealogy">
                  <div class="mb-3">
                    <label for="genealogyName" class="form-label">家谱名称</label>
                    <input 
                      type="text" 
                      class="form-control" 
                      id="genealogyName" 
                      v-model="newGenealogy.genealogyName" 
                      required
                      placeholder="请输入家谱名称"
                    >
                  </div>
                  <div class="mb-3">
                    <label for="genealogyDescription" class="form-label">家谱描述</label>
                    <textarea 
                      class="form-control" 
                      id="genealogyDescription" 
                      v-model="newGenealogy.description" 
                      rows="3"
                      placeholder="请输入家谱描述（选填）"
                    ></textarea>
                  </div>
                </form>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" @click="closeGenealogyForm">取消</button>
                <button type="button" class="btn btn-primary" @click="createNewGenealogy" :disabled="!newGenealogy.genealogyName">创建</button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 模态框背景遮罩 -->
        <div class="modal-backdrop fade show" v-if="showGenealogyForm"></div>
      </div>
      <div class="menu-item" :class="{ active: activeFunction === 'personInfo' }" @click="showPersonManage">
        <i class="fas fa-user"></i>
        <span>家谱人员信息</span>
      </div>
      <div v-if="activeFunction === 'personInfo'" class="person-info">
        <h3>家谱人员信息</h3>
        <ul>
          <li v-for="person in personList" :key="person.id">
            {{ person.name }} - {{ person.relation }}
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { Dropdown } from 'bootstrap'
import axios from 'axios'

export default {
  name: 'HomeView',
  data() {
    return {
      userId: localStorage.getItem('userId') || '',
      activeFunction: null,
      genealogyList: [],
      loading: false,
      error: null,
      selectedGenealogyId: null,
      personList: [],
      genealogyTitle: '',
      showGenealogyForm: false,
      newGenealogy: {
        genealogyName: '',
        description: ''
      }
    }
  },
  mounted() {
    // 初始化所有下拉菜单
    const dropdownElementList = document.querySelectorAll('.dropdown-toggle')
    const dropdownList = [...dropdownElementList].map(dropdownToggleEl => new Dropdown(dropdownToggleEl))
  },
  methods: {
    handleLogout() {
      localStorage.removeItem('isLoggedIn');
      localStorage.removeItem('userId');
      this.$router.push('/login');
    },
    editProfile() {
      // 跳转到编辑个人信息页面
      this.$router.push('/edit-profile');
    },
    createGenealogy() {
      // 显示家谱选择界面
      this.activeFunction = 'familySelect';
      // 加载用户的家谱列表
      this.loadGenealogyData();
    },
    async viewGenealogy() {
      try {
        this.activeFunction = 'familySelect';
        // 加载用户的家谱列表
        await this.loadGenealogyData();
      } catch (error) {
        console.error('获取家谱信息失败:', error);
        alert('获取家谱信息失败，请重试');
      }
    },
    async loadGenealogyData() {
      if (!this.userId) {
        this.error = '用户未登录，无法获取家谱列表';
        return;
      }
      
      try {
        this.loading = true;
        this.error = null;
        
        // 从后端获取用户的家谱列表
        const response = await axios.get(`http://localhost:8080/genealogy/selectAll`);
        
        if (response.data && response.data.code === '200') {
          this.genealogyList = response.data.data || [];
          console.log('获取到家谱列表:', this.genealogyList);
        } else {
          this.error = (response.data && response.data.msg) || '获取家谱列表失败';
          this.genealogyList = [];
        }
      } catch (error) {
        console.error('加载家谱数据错误:', error);
        this.error = '加载家谱列表失败: ' + (error.message || '未知错误');
        this.genealogyList = [];
      } finally {
        this.loading = false;
      }
    },
    selectGenealogy(genealogy) {
      if (!genealogy) return;
      this.selectedGenealogyId = genealogy.genealogyId;
      this.genealogyTitle = genealogy.genealogyName || '未命名家谱';
      
      // 跳转到家谱查看页面
      this.$router.push(`/genealogy/${this.selectedGenealogyId}`);
    },
    async createTestGenealogy() {
      if (!this.userId) {
        this.error = '用户未登录，无法创建家谱';
        return;
      }
      
      // 创建测试数据
      try {
        this.loading = true;
        this.error = null;
        
        const newGenealogy = {
          genealogyName: '测试家谱 ' + new Date().toLocaleTimeString(),
          description: '这是一个测试家谱，创建于 ' + new Date().toLocaleString(),
          createTime: new Date().toISOString()
        };
        
        console.log('创建新家谱:', newGenealogy);
        
        const response = await axios.post('http://localhost:8080/genealogy/add', newGenealogy);
        
        if (response.data && response.data.code === '200') {
          alert('家谱创建成功！');
          // 重新加载家谱数据
          await this.loadGenealogyData();
        } else {
          this.error = (response.data && response.data.msg) || '创建家谱失败';
          console.error('创建家谱失败:', response);
        }
      } catch (error) {
        console.error('创建家谱错误:', error);
        this.error = '创建家谱失败: ' + (error.message || '未知错误');
      } finally {
        this.loading = false;
      }
    },
    backToMain() {
      this.activeFunction = null;
    },
    formatDate(dateString) {
      if (!dateString) return '未知';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    goBack() {
      // 返回上一页
      this.$router.go(-1);
    },
    async showPersonManage() {
      this.activeFunction = 'personInfo';
      if (!this.selectedGenealogyId) {
        alert('请先选择家族');
        return;
      }
      try {
        const response = await axios.get(`http://localhost:8080/genealogyPerson/listByGenealogyId/${this.selectedGenealogyId}`);
        if (response.data.code === '200') {
          this.personList = response.data.data;
        } else {
          this.personList = [];
          alert('获取成员信息失败');
        }
      } catch (e) {
        this.personList = [];
        alert('网络错误');
      }
    },
    showCreateGenealogyForm() {
      this.showGenealogyForm = true;
    },
    closeGenealogyForm() {
      this.showGenealogyForm = false;
    },
    async createNewGenealogy() {
      if (!this.userId) {
        this.error = '用户未登录，无法创建家谱';
        return;
      }
      
      // 创建新家谱
      try {
        this.loading = true;
        this.error = null;
        
        const newGenealogy = {
          genealogyName: this.newGenealogy.genealogyName,
          description: this.newGenealogy.description,
          createTime: new Date().toISOString()
        };
        
        console.log('创建新家谱:', newGenealogy);
        
        const response = await axios.post('http://localhost:8080/genealogy/add', newGenealogy);
        
        if (response.data && response.data.code === '200') {
          alert('家谱创建成功！');
          // 关闭表单
          this.closeGenealogyForm();
          // 重置表单
          this.newGenealogy = {
            genealogyName: '',
            description: ''
          };
          // 重新加载家谱数据
          await this.loadGenealogyData();
        } else {
          this.error = (response.data && response.data.msg) || '创建家谱失败';
          console.error('创建家谱失败:', response);
        }
      } catch (error) {
        console.error('创建家谱错误:', error);
        this.error = '创建家谱失败: ' + (error.message || '未知错误');
      } finally {
        this.loading = false;
      }
    }
  }
}
</script>

<style scoped>
.home-page {
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #0061ff 0%, #ff69b4 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.navbar {
  background: transparent;
  padding: 1rem 0;
  height: 60px;
}

.navbar-brand {
  font-size: 1.5rem;
  font-weight: normal;
  color: white;
}

.nav-link {
  color: white !important;
  font-size: 1rem;
}

.dropdown-menu {
  background: white;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.dropdown-item {
  padding: 0.75rem 1.5rem;
  transition: all 0.3s ease;
}

.dropdown-item:hover {
  background: #f8f9fa;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  padding: 2rem 0;
}

.main-content h1 {
  font-size: 2rem;
  font-weight: normal;
  margin-bottom: 3rem;
}

.operation-cards {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  max-width: 600px;
  margin: 0 auto;
  width: 100%;
  padding: 0 1rem;
}

.operation-card {
  background: white;
  border-radius: 16px;
  padding: 2rem;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.operation-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.icon-wrapper {
  width: 64px;
  height: 64px;
  background: #f0f7ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 1.5rem;
}

.operation-card i {
  font-size: 1.75rem;
  color: #0061ff;
}

.operation-card h2 {
  font-size: 1.5rem;
  color: #333;
  margin-bottom: 0.75rem;
  font-weight: normal;
}

.operation-card p {
  color: #666;
  margin: 0;
  font-size: 1rem;
}

/* 家族选择样式 */
.family-select {
  width: 100%;
  max-width: 700px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16px;
  padding: 20px;
  margin-top: 20px;
}

.family-select h3 {
  color: white;
  margin-bottom: 20px;
  text-align: center;
}

.family-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.family-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.family-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.family-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.add-family {
  background: rgba(255, 255, 255, 0.7);
  border: 2px dashed #0061ff;
}

.family-icon {
  background: #f0f7ff;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.family-icon i {
  color: #0061ff;
  font-size: 1.25rem;
}

.add-icon {
  background: #e6f0ff;
}

.add-icon i {
  color: #0061ff;
}

.family-info {
  flex: 1;
}

.family-info h4 {
  font-size: 1.125rem;
  color: #333;
  margin-bottom: 5px;
}

.family-info p {
  font-size: 0.875rem;
  color: #666;
  margin-bottom: 0;
}

.family-info .description {
  font-style: italic;
  color: #888;
  margin-top: 5px;
}

.menu-item {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16px;
  padding: 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-top: 20px;
}

.menu-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.menu-item i {
  font-size: 1.5rem;
  color: white;
}

.menu-item span {
  font-size: 1rem;
  color: white;
}

.menu-item.active {
  background: rgba(255, 255, 255, 0.2);
}

.person-info {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16px;
  padding: 20px;
  margin-top: 20px;
}

.person-info h3 {
  color: white;
  margin-bottom: 20px;
}

.person-info ul {
  list-style: none;
  padding: 0;
}

.person-info li {
  color: white;
  margin-bottom: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .main-content h1 {
    font-size: 1.75rem;
    margin-bottom: 3rem;
  }

  .operation-card {
    padding: 1.5rem;
  }

  .icon-wrapper {
    width: 56px;
    height: 56px;
    margin-bottom: 1.25rem;
  }

  .operation-card i {
    font-size: 1.5rem;
  }

  .operation-card h2 {
    font-size: 1.25rem;
  }

  .operation-card p {
    font-size: 0.875rem;
  }
  
  .family-select {
    padding: 0 1rem;
  }
  
  .family-info h4 {
    font-size: 1rem;
  }
}
</style> 